package org.bbd.cumi.facade;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.log4j.Logger;
import org.bbd.cumi.bean.Access;
import org.bbd.cumi.bean.AccessExample;
import org.bbd.cumi.bean.Summary;
import org.bbd.cumi.bean.SummaryDateExample;
import org.bbd.cumi.bean.SummaryExample;
import org.bbd.cumi.dao.AccessDao;
import org.bbd.cumi.dao.SummaryDAOImpl;

public class AccessFacade {
	private AccessDao accessDao;
	private SummaryDAOImpl summaryDao;

	private static Logger logger = Logger.getLogger(AccessFacade.class);

	public AccessDao getAccessDao() {
		return accessDao;
	}

	public void setAccessDao(AccessDao accessDao) {
		this.accessDao = accessDao;
	}

	public void parse(InputStream is) throws IOException {
		accessDao.importLog("bbd-proxy", is);
	}

	@SuppressWarnings("unchecked")
	public List<org.bbd.cumi.bean.Summary_Date> listAllSummaryDate() {
		SummaryDateExample example = new SummaryDateExample();
		example.setOrderByClause("YEAR_, MONTH_, DATE_");
		// return this.summaryDateDAO.selectByExample(example);
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Access> listAccessByDate(int year, int month, int date,
			String orderColumn) {
		AccessExample ex = new AccessExample();
		Calendar startDate = new GregorianCalendar(year, month - 1, date);
		Calendar endDate = new GregorianCalendar(year, month - 1, date);
		endDate.add(Calendar.DATE, 1);
		ex.createCriteria().andAccessDateGreaterThanOrEqualTo(
				startDate.getTime()).andAccessDateLessThan(endDate.getTime())
				.andSizeGreaterThan(10 * 1024);
		ex.setOrderByClause(orderColumn);
		return getAccessDao().selectByExample(ex);
	}

	@SuppressWarnings("unchecked")
	public List<Access> listAccessSize(int minSize) {
		AccessExample ex = new AccessExample();
		ex.createCriteria().andSizeGreaterThan(minSize);
		ex.setOrderByClause("SIZE");
		return getAccessDao().selectByExample(ex);
	}

	public SummaryDAOImpl getSummaryDao() {
		return summaryDao;
	}

	public void setSummaryDao(SummaryDAOImpl summaryDao) {
		this.summaryDao = summaryDao;
	}

	@SuppressWarnings("unchecked")
	public List<Summary> summaryEachUrlAllDays() {
		SummaryExample ex = new SummaryExample();
		ex.createCriteria().andYearIsNull().andMonthIsNull().andDateIsNull()
				.andHourIsNull().andClientIpIsNull();
		ex.setOrderByClause("SIZE_ DESC");
		return summaryDao.selectByExample(ex);
	}

	@SuppressWarnings("unchecked")
	public List<Access> getAccessList(String url) {
		AccessExample ex = new AccessExample();
		ex.createCriteria().andUrlEqualTo(url);
		ex.setOrderByClause("access_date desc");
		return accessDao.selectByExample(ex);
	}

	public void deleteAccess(String proxy) {
		accessDao.delete(proxy);
	}

	public void deleteAccess() {
		accessDao.delete();
	}
}
